package patient

import (
	"api-gateway/basic/config"
	proto "api-gateway/basic/proto"
	"api-gateway/handler/request"
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

// GetHospitalList 医院列表
func GetHospitalList(c *gin.Context) {
	var form request.GetHospitalListReq
	if err := c.ShouldBindQuery(&form); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 400, "msg": "参数错误"})
		return
	}

	// 设置分页默认值
	page, pageSize := normalizePage(form.Page, form.PageSize)

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	resp, err := config.PatientClient.GetHospitalList(ctx, &proto.GetHospitalListReq{
		Page:     int32(page),
		PageSize: int32(pageSize),
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 500, "msg": "获取医院列表失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  resp.Message,
		"data": gin.H{
			"total":     resp.Total,
			"hospitals": resp.Hospitals,
		},
	})
}

// GetHospitalDetail 医院详情
func GetHospitalDetail(c *gin.Context) {
	hospitalIdStr := c.Param("id")
	hospitalId, err := strconv.ParseInt(hospitalIdStr, 10, 64)
	if err != nil || hospitalId <= 0 {
		c.JSON(http.StatusOK, gin.H{"code": 400, "msg": "医院ID格式错误"})
		return
	}

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	resp, err := config.PatientClient.GetHospitalDetail(ctx, &proto.GetHospitalDetailReq{
		HospitalId: hospitalId,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 500, "msg": "获取医院详情失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  resp.Message,
		"data": resp.Hospital,
	})
}
